# -*-coding:utf-8 -*-
from django.conf import settings
#import barcode
#from barcode.writer import ImageWriter
import qrcode
from io import BytesIO
import colorsys
from PIL import Image

barcode_format = getattr(settings,'BARCODE_FORMAT',u'code39')


def create_qrcode(value):
    ''' 生成二维码，返回StringIO'''
    qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_L,
        box_size=5,
        border=2,
    )
    qr.add_data(value)
    qr.make(fit=True)
    img = qr.make_image(fill_color="black", back_color="white")
    output = BytesIO()
    img.save(output)
    return output

def create_barcode(value):
    output = BytesIO()
    writer = ImageWriter()
    opts = {'quiet_zone':1,
         'text_distance':1
         }
    coder = barcode.get(barcode_format, value, writer=writer)
    coder.write(output,opts)
    return output


def get_dominant_color(path):
    """ 求图片的rgb值 """
    # 颜色模式转换，以便输出rgb颜色值
    image = Image.open(path).convert('RGBA')
    # image = img.convert('RGBA')
    # 生成缩略图，减少计算量，减小cpu压力
    image.thumbnail((200, 200))

    max_score = None
    dominant_color = None

    for count, (r, g, b, a) in image.getcolors(image.size[0] * image.size[1]):
        # 跳过纯黑色
        # if a == 0:
        #     continue

        saturation = colorsys.rgb_to_hsv(r / 255.0, g / 255.0, b / 255.0)[1]
        y = min(abs(r * 2104 + g * 4130 + b * 802 + 4096 + 131072) >> 13, 235)
        y = (y - 16.0) / (235 - 16)

        # 忽略高亮色
        # if y > 0.9:
        #     continue

        score = (saturation + 0.1) * count

        if score > max_score:
            max_score = score
            dominant_color = (r, g, b)

    return dominant_color
